package com.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.constant.MessageConstant;
import com.exception.CustomException;
import com.mapper.MenuMapper;
import com.pojo.Menu;
import com.pojo.MenuExample;
import com.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

@Service(interfaceClass = MenuService.class)
public class MenuServiceImpl implements MenuService {

    @Autowired
    private MenuMapper menuMapper;


    @Override
    public List<Menu> getMenuAndByUserName(String name) {
        List<Menu> list= name==null?menuMapper.selectByExample(null):menuMapper.getMenuAndByUserName(name);
        List<Menu> menu=new ArrayList<>();
        /*提取父节点*/
        for(Menu m:list){
            if(m!=null && m.getLevel()!=null && m.getLevel()==1){
                for (Menu m2:list){
                    /*提取子节点*/
                    if(m2!=null && m2.getParentmenuid()!=null && m2.getParentmenuid()==m.getId()){
                        m.getChildren().add(m2);
                    }
                }
                menu.add(m);
            }
        }
        return menu;
    }

    @Override
    public List<Menu> queryAll() {
        return menuMapper.queryAll();
    }

    @Override
    public List<Menu> queryByParent() {
        MenuExample me=new MenuExample();
        MenuExample.Criteria mec = me.createCriteria();
        mec.andLevelEqualTo(1);
        return  menuMapper.selectByExample(me);
    }

    @Override
    public void delete(Integer id) throws CustomException {
        //删除前先判断该菜单下面是否有子菜单
        Integer count = menuMapper.queryCount(id);
        if(count>0){
            throw new CustomException(MessageConstant.MENU_PERMISSION_USE);
        }
        menuMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void add(Menu menu) {
        menuMapper.insertSelective(menu);
    }

    @Override
    public void update(Menu menu) {
        menuMapper.updateByPrimaryKeySelective(menu);
    }

    @Override
    public Menu queryById(Integer id) {
        return menuMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Menu> queryAlll() {
        return menuMapper.selectByExample(null);
    }

    @Override
    public Menu queryByParentId(Integer id) {
        MenuExample me=new MenuExample();
        MenuExample.Criteria mec = me.createCriteria();
        mec.andParentmenuidEqualTo(id);
        List<Menu> menus = menuMapper.selectByExample(me);
        return menus!=null && menus.size()>0?menus.get(0):null;
    }
}
